package com.lindroy.androidplayer.base

import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.viewmodel.BaseViewModel
import com.lindroy.androidplayer.ui.dialog.LoadingDialog
import com.lindroy.lib_utils.extensions.getResString


/**
 * @author Lin
 * @date 2021/4/7
 * @function Fragment基类
 */
abstract class BaseFragment : Fragment() {

    private val loadingDialog: LoadingDialog by lazy { LoadingDialog.build(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            initArguments(it)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View = inflater.inflate(layoutId, null)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        registerLoading()
        initView()
        initListener()
        initClick()
    }

    fun showLoading(msg: String = getResString(R.string.loading)) {
        loadingDialog.show(msg)
    }

    fun dismissLoading() {
        Handler().postDelayed({
            loadingDialog.dismiss()
        },500)
    }

    override fun onStop() {
        super.onStop()
    }

    /* private fun registerLoading(showLoading: Boolean = true) {
         showLoading.yes {
             viewModel?.also {
                 it.loadingChange.showDialog.observeInFragment(this) { loadingMsg ->
                     showLoading(loadingMsg)
                 }
                 it.loadingChange.dismissDialog.observeInFragment(this) {
                     dismissLoading()
                 }
             }
         }
     }*/

    /**
     * 注册需要显示加载对话框的ViewModel
     */
    protected fun addLoadingObserve(vararg viewModels: BaseViewModel) {
        viewModels.forEach { viewModel ->
            viewModel.loadingChange.showDialog.observeInFragment(this) {
                showLoading(it)
            }
            viewModel.loadingChange.dismissDialog.observeInFragment(this) {
                dismissLoading()
            }

        }
    }

    abstract val layoutId: Int
    abstract fun initView()
    abstract fun lazyLoad()
    open fun initArguments(bundle: Bundle) {}
    abstract fun initListener()
    abstract fun initClick()
}

interface OnFragmentVisibilityChangedListener {
    fun onFragmentVisibilityChanged(visible: Boolean)
}